using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace Agriculture.Api.Read.Controllers
{
    /// <summary>
    /// 处方流转订单管理
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PrescriptionOrderController : ControllerBase
    {
        private readonly IMediator _mediator;

        public PrescriptionOrderController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 获取处方流转订单列表
        /// </summary>
        /// <param name="patientSearch">患者姓名或手机号</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="orderStatus">订单状态（0：全部，1：待支付，2：已完成，3：已失效）</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>处方流转订单列表</returns>
        [HttpGet]
        public async Task<ApiPageing<PrescriptionOrderDto>> GetPrescriptionOrders(
            [FromQuery] string patientSearch = null,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] int? orderStatus = null,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 10)
        {
            var query = new PrescriptionOrderQuery
            {
                PatientSearch = patientSearch,
                StartTime = startTime,
                EndTime = endTime,
                OrderStatus = orderStatus,
                PageIndex = pageIndex,
                PageSize = pageSize
            };

            var result = await _mediator.Send(query);
            
            return new ApiPageing<PrescriptionOrderDto>
            {
                Code = ApiEnum.Success,
                Msg = "查询成功",
                TotaCount = result.TotalCount,
                TotaPage = result.TotalPages,
                Data = null,
                PageData = result.PrescriptionOrders
            };
        }

        /// <summary>
        /// 获取处方流转订单详情
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns>处方流转订单详情</returns>
        [HttpGet("{orderNo}")]
        public async Task<ApiResult<PrescriptionOrderDetailResult>> GetPrescriptionOrderDetail(string orderNo)
        {
            var query = new PrescriptionOrderDetailQuery
            {
                OrderNo = orderNo
            };

            var result = await _mediator.Send(query);
            
            return new ApiResult<PrescriptionOrderDetailResult>
            {
                Code = result == null ? ApiEnum.Fail : ApiEnum.Success,
                Msg = result == null ? "未找到该订单记录" : "查询成功",
                Data = result
            };
        }
    }
} 